package com.slz.crm.server.interceptor;

import com.slz.crm.common.annotation.RequirePermission;
import com.slz.crm.common.enumeration.PermissionOperates;
import com.slz.crm.common.exiception.BaseException;
import com.slz.crm.common.untils.BaseUnit;
import com.slz.crm.pojo.vo.UserVO;
import com.slz.crm.server.constant.MessageConstant;
import com.slz.crm.server.service.PermissionService;
import com.slz.crm.server.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class PermissionsInterceptor implements HandlerInterceptor {
    @Resource
    private UserService userService;
    @Resource
    private PermissionService permissionService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        if (!(handler instanceof HandlerMethod handlerMethod)) {
            return true;
        }

        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }

        RequirePermission requirePermission = handlerMethod.getMethodAnnotation(RequirePermission.class);
        if (requirePermission == null) {
            return true;
        }

        Long currentId = BaseUnit.getCurrentId();
        UserVO user = userService.getById(currentId);

        if (user.getStatus() != 1) {
            if (user.getRoleId() == 0) {
                throw new BaseException(MessageConstant.USER_IS_FROZEN);
            }
            if (user.getRoleId() == 2) {
                throw new BaseException(MessageConstant.USER_IS_QUIT);
            } else {
                throw new BaseException(MessageConstant.USER_STATUS_ABNORMAL);
            }
        }

        // 如果用户角色ID为1，视为超级管理员，拥有所有权限
        if (user.getRoleId() == 1) {
            return true;
        }

        Enum<? extends PermissionOperates.Operation> targetPerm = null;
        try {
            Class<? extends Enum<?>> permClass = requirePermission.permClass();
            String permName = requirePermission.permName();
            targetPerm = parseEnum(permClass, permName);

        } catch (IllegalArgumentException e) {
            throw new BaseException(MessageConstant.PERM_CONFIG_ERROR);
        }

        // 校验用户是否拥有目标权限
        boolean hasPermission = permissionService.hasPermission(currentId, targetPerm);

        if (!hasPermission) {
            throw new BaseException(MessageConstant.USER_IS_NOT_EXIST_PREM);
        }
        return true;
    }

    /**
     * 安全解析枚举的工具方法：通过泛型封装，解决通配符不兼容问题
     *
     * @param permClass 枚举类（如 CustomerOperate.class）
     * @param permName  枚举项名（如 "CREATE_CUSTOMER"）
     * @return 解析后的枚举实例
     * @throws IllegalArgumentException 若枚举解析失败
     */
    @SuppressWarnings("unchecked")
    private <T extends Enum<T>> Enum<? extends PermissionOperates.Operation> parseEnum(Class<?> permClass, String permName) {
        Class<T> enumType = (Class<T>) permClass;
        return (Enum<? extends PermissionOperates.Operation>) Enum.valueOf(enumType, permName);
    }
}
